<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小恐龙游戏</title>
    <link rel="stylesheet" href="style.css">
</head>
<body id="myDiv">
  <!-- oninput="updateData(this.value)" -->
  <!-- <input type="text" id="myInput" oninput="updateData(this.value)" onkeydown="onkeydowd(event)"> -->
  <p id="myData"></p>
  <div id="gameContainer">
    <div id="dino"></div>
    <div id="obstacle"></div>
    <div id="obstacletwo"></div>
  </div>
  <div class="btn-wai">
    <button id="startbutton" class="startbutton">开始游戏</button>
  </div>
  <script>
    var data = '';
    function updateData(value) {
      data = value;
      document.getElementById('myData').textContent = data;
    }
    function onkeydowd (event) {
      document.getElementById('myData').textContent = '用户按下了：'+event.key+'键';
    }
    // 获取div元素
    var myDiv = document.getElementById('myDiv');
    const dino = document.getElementById('dino');
    const obstacle = document.getElementById('obstacle');
    const obstacletwo = document.getElementById('obstacletwo');
    const startbutton = document.getElementById('startbutton');
    
    // 为div注册键盘按下事件
    myDiv.addEventListener('keydown', function(event) {
      // 输出按下的键盘按键
      if (event.key === "w") {

        console.log('Key pressed:', event.key);
        if (!dino.classList.contains('jump')) { // 防止在空中多次跳跃
          dino.classList.add('jump');
          setTimeout(() => {
            dino.classList.remove('jump');
          }, 500); // 跳跃时间与CSS动画持续时间相同
        }
      }
      console.log(event.key);
    });
      
    /* 确保div可以聚焦 */ 
    myDiv.addEventListener('click', function() {
      this.focus();
    });
    /* 开始游戏 */ 
    startbutton.addEventListener('click', function(event) {
      document.getElementById('obstacle').style.animation = 'moveObstacle 2s infinite linear';
      setTimeout(() => {
        document.getElementById('obstacletwo').style.animation = 'moveObstacletwo 2s infinite linear';
      },1000)
    });
    /* 碰撞检测 */
    let checkCollision = setInterval(function() {
      let dinoTop = parseInt(window.getComputedStyle(dino).getPropertyValue("bottom"));
      let obstacleLeft = parseInt(window.getComputedStyle(obstacle).getPropertyValue("left"));
      let obstacleLefttwo = parseInt(window.getComputedStyle(obstacletwo).getPropertyValue("left"));
      // 检测碰撞
      if(obstacleLeft > 0 && obstacleLeft < 20 && dinoTop < 30) {
        // 移除样式
        document.getElementById('obstacle').removeAttribute('style');
        alert("游戏结束！");
      }
      // 检测碰撞
      if(obstacleLefttwo > 0 && obstacleLefttwo < 20 && dinoTop < 30) {
        // 移除样式
        document.getElementById('obstacletwo').removeAttribute('style');
        alert("游戏结束！");
      }
    }, 10);
  </script>
</body>
</html>